//
// Created by mi on 2024/5/1.
//
#include <optional>
#include <iostream>

using namespace std;

optional<int> getData(bool giveIt)
{
    if (giveIt) {
        return 42;
    }

    return nullopt;  // or simply return {};
}
// std::optional 是 C++17 中引入的标准库模板类。它提供了一种表示可选值的方式，也就是值可能存在，也可能不存在。它属于 <optional> 头文件。
int main()
{
    auto data1 = getData(true);
    auto data2 = getData(false);

    cout << "data1.has_value = " << data1.has_value() << endl;
    if (data2) {
        cout << "data2 has a value." << endl;
    }

    cout << "data1.value = " << data1.value() << endl;
    cout << "data1.value = " << *data1 << endl;

    try {
        cout << "data2.value = " << data2.value() << endl;
    } catch (const bad_optional_access& ex) {
        cout << "Exception: " << ex.what() << endl;
    }

    cout << "data2.value = " << data2.value_or(0) << endl;

    return 0;
}